import type { RouteTabItem } from '@/types/index.ts';
import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useRouteTabStore = defineStore('route-tab', () => {
	const routeTabs = ref<RouteTabItem[]>([]);
	const activeKey = ref<string>('');
	const add = (route: RouteTabItem) => {
		if (!routeTabs.value.find((v) => v.key === route.key)) {
			routeTabs.value.push(route);
		}
		activeKey.value = route.key;
	};
	const remove = (key: string) => {
		const index = routeTabs.value.findIndex((v) => v.key === key);
		const newActiveIndex = index - 1;
		routeTabs.value = routeTabs.value.filter((v) => v.key !== key);
		if (routeTabs.value.length > 0 && activeKey.value === key) {
			if (newActiveIndex >= 0) {
				activeKey.value = routeTabs.value[newActiveIndex].key;
			} else {
				activeKey.value = routeTabs.value[0].key;
			}
		}
		if (!routeTabs.value.length) {
			activeKey.value = '/home';
		}
	};
	return {
		routeTabs,
		add,
		remove,
		activeKey,
	};
});
